import axios, { AxiosResponse } from 'axios';

// 配置axios默认设置
axios.defaults.baseURL = 'http://localhost:8080/api';
axios.defaults.timeout = 10000;

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 统一响应接口
export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

// 用户信息接口
export interface UserInfo {
  id: number;
  username: string;
  nickname: string;
  email: string;
  phone: string;
  avatar: string;
  status: number;
  createTime: string;
  lastLoginTime: string;
  roles: string[];
  token: string;
}

// 登录请求接口
export interface LoginRequest {
  username: string;
  password: string;
  rememberMe?: boolean;
}

// 注册请求接口
export interface RegisterRequest {
  username: string;
  password: string;
  confirmPassword: string;
  nickname?: string;
  email?: string;
  phone?: string;
}

// 认证API服务
export const authApi = {
  // 用户登录
  login: (data: LoginRequest): Promise<ApiResponse<UserInfo>> => {
    return axios.post('/auth/login', data).then(res => res.data);
  },

  // 用户注册
  register: (data: RegisterRequest): Promise<ApiResponse<string>> => {
    return axios.post('/auth/register', data).then(res => res.data);
  },

  // 用户登出
  logout: (): Promise<ApiResponse<string>> => {
    return axios.post('/auth/logout').then(res => res.data);
  },

  // 获取当前用户信息
  getCurrentUser: (): Promise<ApiResponse<UserInfo>> => {
    return axios.get('/auth/userinfo').then(res => res.data);
  },

  // 刷新token
  refreshToken: (): Promise<ApiResponse<string>> => {
    return axios.post('/auth/refresh').then(res => res.data);
  },

  // 健康检查
  healthCheck: (): Promise<ApiResponse<string>> => {
    return axios.get('/health').then(res => res.data);
  }
};

export default axios;